/**
 * 
 */
package com.activities;


import java.io.File;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableRow;
import android.widget.TextView;
import com.Adapters.AlbumAdapter;
import com.Animations.AnimUtil;
import com.Animations.AnimationLists;
import com.Data.Albums;
import com.Data.Albums.onAddCompleted;
import com.Data.Albums.onDeleteCompleted;
import com.Data.Albums.onGetCompleted;
import com.Dialogs.DialogManagerClass;
import com.Dialogs.DialogManagerClass.onNewAlbumNamed;
import com.Downloaders.ThumbDownloader;
import com.Downloaders.ThumbDownloader.ThumbnailPathCompleted;
import com.Enums.BlurType;
import com.Managers.DirManagerClass;
import com.Managers.FragmentManagerClass;
import com.Managers.PictureManagerClass.CreateBlurAsync;
import com.Managers.ThemeManager;
import com.Managers.UserManagerClass;
import com.PopUps.PopUpClass;
import com.TextFormat.UtilFonts;
import com.shareup.R;
import com.utils.AppConstant;
import com.utils.ShowToastClass;
import com.utils.Utils;


/**
 * @author Chris
 * 
 */
public class ActivityAlbums extends FragmentActivity implements DefaultFunctions, AlbumFunctions {

    public static int ALBUM_INDEX;

    private static Albums albumCover;

    public static void delayGet(final Albums al) {

        Handler myHandler = new Handler();
        myHandler.postDelayed(new Runnable() {

            @Override
            public void run() {

                al.execute();

            }

        }, 1000);
    }

    public void hideInfo() {

        AnimUtil.AnimateDrawablesIn(newB, getResources().getDrawable(R.drawable.selector_button_add_light));
        newB.setOnClickListener(newClick);

    }

    private static int FROM_BACK = 7001;

    private static int FROM_RESULT = 7002;

    private TextView title;

    public boolean isExpectingResult;

    private AlbumAdapter adapter;

    private int columnWidth;

    private GridView gridView;

    private boolean isExploring;

    private boolean justExit;

    private ImageView coverLayout;

    public boolean isExploring() {

        return this.isExploring;
    }

    public void setExploring(boolean isExploring) {

        this.isExploring = isExploring;

        justExit = true;
    }

    private void downloadCover(Albums al) {

        String path = al.getCover();
        String idActualCover = "";
        if (albumCover != null)
            idActualCover = albumCover.getCover();

        if (!path.equals("0") && al.getPin() == 0
                    && !idActualCover.equals(al.getCover())) {

            albumCover = al;
            path = path.replace("cache/", "");

            String ps = DirManagerClass.getSDPath()
                        + DirManagerClass.ThumbsPath;
            ps += DirManagerClass.getPictureNameWE(path);

            if (new File(ps).exists())
                createBlur(ps);
            else {

                ThumbDownloader td = new ThumbDownloader(this, path);
                td.setCompletePath(new ThumbnailPathCompleted() {

                    @Override
                    public void Completed(String path) {

                        createBlur(path);

                    }
                });
                td.execute();
            }
        }

    }

    private void createBlur(String path) {

        int Blur = BlurType.BLUR_COVER.getValue();
        CreateBlurAsync cbs = new CreateBlurAsync(Blur, coverLayout, path);
        cbs.setUserProfile(true);
        cbs.execute();
    }

    private LinearLayout listContainer;

    private Albums selectedAlbum;

    private ImageView newB;

    private boolean hasDeleted;

    private OnClickListener newClick = new OnClickListener() {

        @Override
        public void onClick(View v) {

            showDialogNewAlbum();
        }
    };

    private TableRow table;

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#clear()
     */
    @Override
    public void clear() {

        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#contains(int)
     */
    @Override
    public boolean contains(int object) {

        // TODO Auto-generated method stub
        return false;
    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#getParentActivity()
     */
    @Override
    public Activity getParentActivity() {

        return this;
    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#Init()
     */
    @Override
    public void Init() {

        gridView = (GridView) findViewById(R.id.list_thumb);
        InitilizeGridLayout();
        //
        listContainer = (LinearLayout) this.findViewById(R.id.list_container);
        table = (TableRow) findViewById(R.id.message_container);
        title = (TextView) findViewById(R.id.title_actionbar);
        UtilFonts.setTextBoldFont(title);
        if (isExpectingResult)
            title.setText(getResources().getString(R.string.crop_albums_select_title));
        // BUTTON BACK
        ImageView backB = (ImageView) findViewById(R.id.button_back);
        newB = (ImageView) findViewById(R.id.button_new);
        // LISTENER BUTTON BACK
        backB.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                exit(FROM_BACK);
            }
        });
        newB.setOnClickListener(newClick);
        coverLayout = (ImageView) findViewById(R.id.coverView);
        //
        getAlbums();

    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#loadFrom(int)
     */
    @Override
    public void loadFrom(int SoapUtilMode, int index) {

        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#loadFromTags(java.lang.String)
     */
    @Override
    public void loadFromTags(String tag) {

        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#onConnection()
     */
    @Override
    public void onConnection() {

        // TODO Auto-generated method stub

    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit(FROM_BACK);
            //
            return true;
        }
        //
        return super.onKeyUp(keyCode, event);
    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#onNoConnection()
     */
    @Override
    public void onNoConnection() {

        // TODO Auto-generated method stub

    }

    public void putResult(int Result, Albums album) {

        Intent intent = new Intent();
        intent.putExtra("ALBUM_ID", album.getID());
        intent.putExtra("albumName", album.getName());

        String cover = album.getCover();
        if (album.getCover() != null && !album.getCover().equals("0")) {
            String[] sp = album.getCover().split("/");
            cover = sp[sp.length - 1].replace(".jpg", "");

        }
        else
            cover = "0";

        intent.putExtra("ALBUM_COVER", cover);

        setResult(Result, intent);

        exit(FROM_RESULT);
    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#refresh()
     */
    @Override
    public void refresh() {

        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#remove(java.lang.Object)
     */
    @Override
    public void remove(Object object, onDeleteCompleted callback) {

        Albums al = ((Albums) object);
        Albums album = new Albums();
        album.setID(al.getID());
        album.setOwner(al.getOwner());
        album.setCallbackDelete(callback);
        album.setMode(Albums.ACTION_DELETE);
        album.execute();

    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#resultList(java.lang.Object[])
     */
    @Override
    public void resultList(Object[] result) {

        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#setLoading()
     */
    @Override
    public void setLoading() {

        PopUpClass up = new PopUpClass(this);
        up.setLoadingList(table);

    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#setMessage(java.lang.String, int)
     */
    @Override
    public void setMessage(String message, int iconResource) {

        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#setNoItemsMessage()
     */
    @Override
    public void setNoItemsMessage() {

        // TODO Auto-generated method stub

    }

    public void setNoItemsPopUp() {

        PopUpClass up = new PopUpClass(this);
        up.setMessage(getResources().getString(R.string.dialog_no_albums), R.drawable.notification_normal, table);

    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#stopLoading()
     */
    @Override
    public void stopLoading() {

        AnimUtil.animatePopUp(table, false, null);

    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#updateComments(int, int)
     */
    @Override
    public void updateComments(int objectId, int count) {

        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#updateLikes(int, int)
     */
    @Override
    public void updateLikes(int objectId, int count) {

        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#updatePermissions(int, int)
     */
    @Override
    public void updatePermissions(int id, int newPermissions) {

        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#updateTime(int)
     */
    @Override
    public void updateTime(int id) {

        // TODO Auto-generated method stub

    }

    private void addNewAlbum(final String name, int pin, int privacy) {

        Albums al = new Albums(Albums.ACTION_ADD);
        al.setContext(this);
        al.setOwner(UserManagerClass.UserLogged);
        al.setCallbackAdd(new onAddCompleted() {

            @Override
            public void Completed(String result) {

                if (result.equals("-20"))
                    albumExists();
                else
                    if (isExpectingResult) {
                        Albums album = new Albums();
                        album.setID(Integer.parseInt(result));
                        album.setName(name);
                        putResult(RESULT_OK, album);
                    }

                    else
                        getAlbums();

            }
        });
        al.setName(name);
        al.setPin(pin);
        al.setPrivacy(privacy);
        al.setCover("0");
        al.execute();
    }

    private void addToList(Albums[] result) {

        if (adapter == null)
            adapter = new AlbumAdapter(columnWidth, this, R.id.name, this, this);

        if (gridView.getAdapter() == null) {
            gridView.setAdapter(adapter);
            gridView.setOnScrollListener(adapter);
        }

        boolean changes = false;
        for (Albums al : result) {

            if (!adapter.contains(al)) {
                adapter.add(al);
                changes = true;

            }

        }
        if (changes)
            adapter.notifyDataSetChanged();

        stopLoading();

        if (adapter.getCount() == 0)
            setNoItemsPopUp();
        else
            downloadRandomCover();

    }

    private void downloadRandomCover() {

        if (adapter.getCount() > 0) {
            Random rn = new Random();
            int num = rn.nextInt(adapter.getCount());
            Albums al = adapter.getItem(num);

            int cont = 0;
            if (al.getPin() != 0)
                while (al.getPin() != 0 && !al.getCover().equals("0")
                            || cont != adapter.getCount()) {

                    num = rn.nextInt();
                    al = adapter.getItem(num);

                }

            downloadCover(al);

        }
        else
            removeCover();

    }

    private void albumExists() {

        ShowToastClass.message(getResources().getString(R.string.error_album_exists), this);
    }

    private void getBackAlbums() {

        listContainer.removeAllViews();
        listContainer.addView(gridView);
        if (FragmentManagerClass.aExploreAlbum != null) {
            FragmentManager manager = FragmentManagerClass.aExploreAlbum.getFragmentManager();
            FragmentTransaction trans = manager.beginTransaction();
            trans.remove(FragmentManagerClass.aExploreAlbum);
            trans.commit();
            FragmentManagerClass.aExploreAlbum = null;
        }

        isExploring = false;
        hideInfo();
        this.title.setText(getResources().getString(R.string.crop_my_albums_title));

    }

    private void exit(int from) {

        if (hasDeleted && from == FROM_BACK && !justExit) {

            hasDeleted = false;
            if (isExpectingResult) {
                isExpectingResult = false;
                putResult(Activity.RESULT_OK, new Albums());

            }

        }
        else
            if (isExploring)
                getBackAlbums();

            else {
                AnimationLists.displayedImages.clear();
                AnimationLists.displayedThumbs.clear();
                finish();
                AnimUtil.getActivityTransition(this, false);
            }

    }

    private void getAlbums() {

        setLoading();

        Albums al = new Albums(Albums.ACTION_GET);
        al.setOwner(UserManagerClass.UserLogged);
        al.setCallbackGet(new onGetCompleted() {

            @Override
            public void Completed(Albums[] result) {

                addToList(result);
            }
        });
        delayGet(al);
    }

    private void InitilizeGridLayout() {

        Resources r = getResources();
        float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, AppConstant.GRID_PADDING, r.getDisplayMetrics());

        Utils utils = new Utils(this);
        columnWidth = (int) ((utils.getScreenWidth() - ((AppConstant.NUM_OF_COLUMNS + 1) * padding)) / AppConstant.NUM_OF_COLUMNS);

        gridView.setNumColumns(AppConstant.NUM_OF_COLUMNS);
        gridView.setColumnWidth(columnWidth);
        gridView.setStretchMode(GridView.NO_STRETCH);
        gridView.setPadding((int) padding, (int) padding, (int) padding, (int) padding);
        gridView.setHorizontalSpacing((int) padding);
        gridView.setVerticalSpacing((int) padding);
    }

    private void showDialogNewAlbum() {

        DialogManagerClass.showAddAlbumDialog(this, new onNewAlbumNamed() {

            @Override
            public void Named(String name, int pin, int privacy) {

                addNewAlbum(name, pin, privacy);

            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        ThemeManager.setTheme(this);
        setContentView(R.layout.activity_albums);
        super.onCreate(savedInstanceState);

        if (getCallingActivity() != null)
            isExpectingResult = true;

        Init();

    }

    @Override
    protected void onDestroy() {

        FragmentManagerClass.aAlbum = null;

        super.onDestroy();
    }

    @Override
    protected void onResume() {

        FragmentManagerClass.aAlbum = this;

        if (!isExploring)
            getBackAlbums();

        super.onResume();
    }

    /*
     * (non-Javadoc)
     * @see com.activities.AlbumFunctions#setAlbum(com.Data.Albums)
     */
    @Override
    public void setAlbum(Albums selected) {

        hasDeleted = false;

        this.selectedAlbum = selected;
        this.title.setText(selected.getName());
        adapter.updateItemAlbum(selected);

        if (isExpectingResult)
            putResult(Activity.RESULT_OK, selected);

    }

    public Albums getAlbum() {

        return selectedAlbum;
    }

    /*
     * (non-Javadoc)
     * @see com.activities.AlbumFunctions#setThumSelected(java.lang.Object)
     */
    @Override
    public void setThumSelected(Object selected) {

        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     * @see com.activities.AlbumFunctions#showInfo(com.Data.Albums)
     */
    @Override
    public void showInfo(Albums selected) {

        Intent intent = new Intent(this, ActivityAlbumInfo.class);
        ActivityAlbumInfo.album = selected;
        startActivity(intent);
        AnimUtil.getActivityTransition(this, true);

    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#remove(java.lang.Object)
     */
    @Override
    public void remove(Object object) {

        Albums al = (Albums) object;

        hasDeleted = true;
        adapter.remove(al);

        if (albumCover != null && al.getID() == albumCover.getID()) {
            albumCover = null;
            downloadRandomCover();

        }

    }

    private void removeCover() {

        AnimUtil.AnimateDrawablesOutImage(coverLayout);
        albumCover = null;

    }

}
